<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFunc"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFunc"
        >查询</el-button
      >
      <el-button
        size="mini"
        v-functions="['sms_config_tmpl_insert']"
        @click="addAutographFun"
        >新增</el-button
      >
    </template>
    <template slot="content">
      <configTable
        v-if="isShowTabel"
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        :headersConfig="true"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="
                !['oprate', 'status', 'smsType'].includes(item.prop) &&
                item.show
              "
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :show-overflow-tooltip="true"
            >
            </u-table-column>
            <u-table-column
              v-if="['smsType'].includes(item.prop) && item.show"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">
                <span>{{ row.smsType | getSmsTypeName }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="['status'].includes(item.prop) && item.show"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">
                <span>
                  <i
                    class="circle"
                    :style="{
                      background: row.statusObj && row.statusObj.color,
                    }"
                  />
                  {{ row.statusObj && row.statusObj.statusName }}
                </span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="['oprate'].includes(item.prop) && item.show"
              :key="index"
              :label="item.label"
              :width="100"
              fixed="right"
            >
              <template slot-scope="{ row }">
                <span
                  v-show="row.status !== 2"
                  class="oprate-span"
                  v-functions="['sms_config_tmpl_edit']"
                  @click="handleEdit(row)"
                  >编辑</span
                >
                <span
                  class="oprate-span red-span"
                  v-functions="['sms_config_tmpl_delete']"
                  @click="handleDelete(row)"
                  >删除</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <AddOrEditTemplet
        ref="createTemplet"
        @updateTempletList="handleSearchFunc"
      />
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import { deepClone, isHasFuncOrMenus, getFormatDateTime, commonAction } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import AddOrEditTemplet from './addTemplet.vue'
import { v4 as uuidv4 } from 'uuid'
@Component({
  name: 'smsConfigTmpl',
  components: {
    QuickSearch,
    configTable,
    continer,
    AddOrEditTemplet
  },
  filters: {
    getSmsTypeName (val) {
      switch (val) {
        case 'validateCode':
          return '验证码'
        case 'notice':
          return '通知短信'
        case 'marketing':
          return '营销短信'
      }
    }
  }
})
export default class CustomerTemplateSetting extends Vue {
  [x: string]: any
  @Ref() private readonly createTemplet

  private tableData: any = []

  private pagingData: any = {
    page: 1,
    limit: 10,
    total: 0
  }

  private isShowTabel: boolean = false

  private checkHeaders: any = []

  private tableHeaders: any = [
    {
      label: '模板ID',
      prop: 'id',
      show: true
    },
    {
      label: '模板名称',
      prop: 'displayName',
      show: true
    },
    {
      label: '短信类型',
      prop: 'smsType',
      show: true
    },
    {
      label: '模板内容',
      prop: 'content',
      show: true
    },
    {
      label: '场景说明',
      prop: 'sceneDescription',
      show: true
    },
    {
      label: '创建时间',
      prop: 'createTime',
      show: true
    },
    {
      label: '创建人',
      prop: 'operator',
      show: true
    },
    {
      label: '审核状态',
      prop: 'status',
      show: true
    },
    {
      label: '审核失败原因',
      prop: 'reason',
      show: true
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  private smsType: any = [
    {
      name: '验证码',
      key: 'validateCode'
    },
    {
      name: '通知短信',
      key: 'notice'
    },
    {
      name: '营销短信',
      key: 'marketing'
    }
  ]

  private templetStatus: any = [
    {
      name: '审核中',
      key: 1
    },
    {
      name: '已通过',
      key: 2
    },
    {
      name: '未通过',
      key: 3
    }
  ]

  private quickSearchForm: any = {
    form: {
      query: '',
      createTimeQueryArray: [ // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 6), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
      ],
      smsType: '',
      status: ''
    },
    advSearchOptions: [
      { label: '模板搜索', name: 'query', inputType: 'input', clearable: true, placeholder: '请输入ID或模板名称' },
      { label: '短信类型', name: 'smsType', inputType: 'select', clearable: true, multiple: false, selectData: this.smsType, placeholder: '请选择', defaultProp: { label: 'name', value: 'key' } },
      { label: '状态', name: 'status', inputType: 'select', clearable: true, multiple: false, selectData: this.templetStatus, placeholder: '请选择', defaultProp: { label: 'name', value: 'key' } },
      { label: '创建时间', name: 'createTimeQueryArray', inputType: 'dateTimeRange', clearable: true }
    ]
  }

  get getAccountId () {
    return (CommonModule as any).session.user.accountId || ''
  }

  private getStatusName (val) {
    switch (val) {
      case 1:
        return { statusName: '审核中', color: '#ffbf00' }
      case 2:
        return { statusName: '已通过', color: '#2ed47a' }
      case 3:
        return { statusName: '未通过', color: '#fc6b5c' }
    }
  }

  private getAgentName (agentId) {
    const agent = (CommonModule as any).publicCache.userListObj[agentId]
    if (agent) {
      return agent.name
    }
    return ''
  }

  private getUUID () {
    return uuidv4().replace(/-/g, '')
  }

  private checkHeadersChange (checkList: any, isInit: any) {
    this.$set(this, 'checkHeaders', checkList)
    if (!isInit) {
      this.saveTabelHeaders(checkList)
    }
  }

  private saveTabelHeaders (headers: any) { // 自定义表头保存
    if (headers[headers.length - 1].prop === 'oprate') { // 如果表头最后一项是操作需去掉，操作不入库
      headers = headers.slice(0, headers.length - 1)
    }
    const data = {
      url: '/base/action/header',
      method: 'POST',
      data: {
        type: 'sms_tmpl',
        config: headers
      }
    }
    commonAction(data)
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.initData()
  }

  private initData () {
    const actionData = {
      url: '/sms-api/sms/manager/template/list',
      method: 'POST',
      data: {
        page: this.pagingData.page,
        pageSize: this.pagingData.limit,
        action: 'MANAGER_TEMPLATE_QUERY',
        requestId: this.getUUID(),
        param: {
          customer: this.getAccountId,
          ...this.quickSearchForm.form
        }
      }
    }
    commonAction(actionData).then(res => {
      if (res.code === '0000200' && res.data) {
        res.data.list.forEach(item => {
          item.statusObj = this.getStatusName(item.status)
          item.operator = this.getAgentName(item.operator)
        })
        this.tableData = res.data.list
        this.pagingData.total = res.data.total
      }
    })
  }

  private handleEdit (row: any) {
    this.$nextTick(() => {
      this.createTemplet.openDrawer('edit')
      this.createTemplet.formData = deepClone(row)
      console.log(this.createTemplet.formData, 88)
    })
  }

  private addAutographFun () {
    this.$nextTick(() => {
      this.createTemplet.clearData() // 清空数据
      this.createTemplet.openDrawer('add')
    })
  }

  private handleDelete (row: any) {
    this.$confirm('短信模板删除后，不能再次使用该模板发送短信，请谨慎删除', '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const params = {
        url: '/sms-api/sms/manager/template/del',
        method: 'POST',
        data: {
          action: 'MANAGER_TEMPLATE_REMOVE',
          requestId: this.getUUID(),
          param: {
            ids: [row.id]
          }
        }
      }
      commonAction(params).then(res => {
        if (res.code === '0000200') {
          this.$message.success('删除成功')
          this.initData()
        }
      })
    })
  }

  private handleSearchFunc () {
    this.pagingData.page = 1
    this.initData()
  }

  private getTabelHeaders () { // 获取自定义表头
    this.isShowTabel = false
    const params = { url: '/base/action/header', method: 'GET', data: { type: 'sms_tmpl' } }
    commonAction(params).then((res: any) => {
      if (res.success && res.data && res.data.config && res.data.config.length) {
        res.data.config.push({ label: '操作', prop: 'oprate', disenable: true })
        this.$set(this, 'tableHeaders', res.data.config)
      }
      this.$nextTick(() => {
        this.isShowTabel = true
      })
    })
  }

  private mounted () {
    this.getTabelHeaders()
    this.initData()
  }
}
</script>
<style lang="stylus" scoped>
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
.red-span
  color $c-danger
.circle
  width 6px
  height 6px
  border-radius 50%
  display inline-block
  margin-right 5px
</style>
